package com.itboye.ihomebank.activity.key;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.adapter.key.KeyTwoAdapter;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.KeysBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.SIDBean;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.custom.MyListView;
import com.itboye.ihomebank.interfaces.IRefreshAfterAlert;
import com.itboye.ihomebank.presenter.KeyPresenter;
import com.itboye.ihomebank.presenter.KeyTwoPresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.ttKey.DaoMaster;
import com.itboye.ihomebank.ttKey.DaoSession;
import com.itboye.ihomebank.ttKey.DbService;
import com.itboye.ihomebank.ttKey.Key;
import com.itboye.ihomebank.ttKey.KeyDao;
import com.itboye.ihomebank.ttKey.MyPreference;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.SaveKeyBean;

import org.greenrobot.greendao.database.Database;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import static com.itboye.ihomebank.util.SPUtils.get;
import static com.ttlock.bl.sdk.util.GsonUtil.gson;
import static java.lang.Long.parseLong;

/**
 * Created by Administrator on 2018/8/14 0014.
 */

public class ActivityKeyXuanZe extends BaseOtherActivity implements Observer{
    MyListView xlistview;
    View v_statusbar;
    ImageView close_icon;// 返回图片
    TextView add_shap_title_tv;// 标题
    private KeyTwoAdapter adapter;// 钥匙适配器
    private List<Key> keys;//本地缓存的钥匙

    private KeyPresenter presenter;
    private UserPresenter userPresent;
    private String uid;

    public static KeyDao keyDao;
    private List<KeysBean> kensBean;
    private DaoSession daoSession;
    private boolean isLock;
    private String sid;
    @Override
    protected int layout_id() {
        return R.layout.activity_key_xuan_ze;
    }

    @Override
    protected void onInitController() {

    }

    /**
     * 数据库初始化
     */
    private void initGreenDao() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "zhujias.db", null);
        Database db = helper.getWritableDb();
        daoSession = new DaoMaster(db).newSession();
        keyDao = daoSession.getKeyDao();
    }

    @Override
    protected void onInit() {
        setStatusBarHeight(v_statusbar);
        add_shap_title_tv.setText("选择要常用的钥匙");
        presenter=new KeyPresenter(this);
        userPresent=new UserPresenter(this);
        isLock= (boolean) SPUtils.get(MyApplcation.ctx,null,SPContants.ISLOCK,false);

        keys = new ArrayList<Key>();
        kensBean=new ArrayList<>();
        uid = get(this, null, SPContants.USER_ID, "") + "";

        keys = DbService.getKeysByLockAlias("");
        sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
        if ("".equals(sid)){
            presenter.myKey(uid, "",isLock);
        }else {
            presenter.myKey(sid, "",isLock);
        }



        xlistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                Bundle bundle=new Bundle();
                bundle.putSerializable("key",keys.get(position));
                bundle.putString("mac",keys.get(position).getLockMac());
                bundle.putString("type",keys.get(position).getTypes());
                intent.putExtras(bundle);
                setResult(105, intent);
                finish();
            }
        });
        initGreenDao();
    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity!=null){

            if (entity.getEventType()== KeyPresenter.mykeys_success){
                kensBean = (List<KeysBean>) entity.getData();
                Log.d("=====keji==",kensBean.toString());
                if (kensBean != null) {
                    if (kensBean.size() > 0) {
                        keys.clear();
                        //清空本地并重新保存数据
                        DbService.deleteAllKey();
                        for (int i = 0; i < kensBean.size(); i++) {
                            xlistview.setVisibility(View.VISIBLE);
                            Key key = new Key();
                            key.setAccessToken(MyPreference.getStr(mContext,
                                    MyPreference.ACCESS_TOKEN));
                            if (kensBean.get(i).getType().equals("0")) {
                                key.setAdmin(true);
                            } else {
                                key.setAdmin(false);
                            }
                            key.setLockVersion(gson.toJson(kensBean.get(i).getLock_version()));
                            key.setLockName(kensBean.get(i).getLock_name());
                            key.setLockMac(kensBean.get(i).getLock_mac());
                            key.setAdminPs(kensBean.get(i).getAdminPwd());
                            key.setUnlockKey(kensBean.get(i).getLock_key());
                            key.setAdminKeyboardPwd(kensBean.get(i).getNoKeyPwd());
                            key.setDeletePwd(kensBean.get(i).getDeletePwd());
                            key.setPwdInfo("");
                            key.setTimestamp(0);
                            key.setAesKeystr(kensBean.get(i).getAesKeyStr());
                            // key.setTimezoneRawOffset(TimeZone.getDefault().getOffset(currentTimeMillis()));
                            key.setTimezoneRawOffset(Integer.parseInt(get(this, null, SPContants.SHIQU, "") + ""));

                            //上面是开锁用到的必要数据，下面这些是一些操作数据
                            key.setLockId(kensBean.get(i).getLock_id());
                            key.setKeyId(kensBean.get(i).getKey_id());
                            key.setLockAlias(kensBean.get(i).getLock_alias());
                            key.setStartDate(parseLong(kensBean.get(i).getStart()));
                            key.setEndDate(parseLong(kensBean.get(i).getEnd()));

                            key.setUser_type(kensBean.get(i).getUser_type());
                            key.setStatus(kensBean.get(i).getStatus());
                            key.setPush(kensBean.get(i).getPush());
                            key.setHouse_no(kensBean.get(i).getHouse_no());
                            key.setTypes(kensBean.get(i).getType());
                            key.setKeyStatus(kensBean.get(i).getKeyStatus());
                            key.setBattery(kensBean.get(i).getPower());
                            key.setLock_type(kensBean.get(i).getLock_type());
                            key.setHas_valid_rent(kensBean.get(i).getHas_valid_rent());
                            key.setReset_rent_pass(kensBean.get(i).getReset_rent_pass());
                            key.setId(keyDao.insert(key));
                            keys.add(key);
                        }
                        //清空本地并重新保存数据
                        DbService.saveKeyList(keys);

                        adapter = new KeyTwoAdapter(this, keys);
                        xlistview.setAdapter(adapter);
                        adapter.notifyDataSetChanged();

                        //解绑锁的数据，如果没有网，上传没成功，存在本地；如果上传成功了   就删除
                        String jKeyid = get(this, null, SPContants.J_KEYID, "") + "";
                        String jLockid = get(this, null, SPContants.J_LOCKID, "") + "";
                        String aesKeyStr = get(this, null, SPContants.AESKEYSTR, "") + "";
                        for (int j = 0; j < kensBean.size(); j++) {
                            String s1 = kensBean.get(j).getLock_id();
                            String s2 = kensBean.get(j).getKey_id();
                            String s3 = kensBean.get(j).getAesKeyStr();
                            if (s1.equals(jLockid) && s2.equals(jKeyid) && s3.equals(aesKeyStr)) {
                                userPresent.unbindLock(uid, jLockid, jKeyid, "");
                            }
                        }

                    }
                }
            }else if (entity.getEventType()==KeyPresenter.mykeys_fail){
                if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert(entity.getMsg());
                }

            }
            // 解除绑定
            else if (entity.getEventType() == UserPresenter.unbindAdmin_success) {
//                SaveKeyBean.saveDataTwo("2", null);
//                ByAlert.alert(entity.getData());
//                String accessToken = MyPreference.getStr(mContext, MyPreference.ACCESS_TOKEN);
//                Key localKey = DbService.getKeyByAccessTokenAndLockmac(accessToken, jiebangKey);
//                //删除本地钥匙(不删除本地钥匙，会导致下次绑定同一锁时导致无效)
//                DbService.deleteKey(localKey);
//                presenter.myKey(uid,"");
//                Iterator<Key> iterator = keys.iterator();
//                while (iterator.hasNext()) {
//                    Key bean = iterator.next();
//                    if (deKeyId.equals(bean.getKeyId())) {
//                        iterator.remove();
//                        adapter.notifyDataSetChanged();
//                        break;
//                    }
//                }
            } else if (entity.getEventType() == UserPresenter.unbindAdmin_fail) {
                ByAlert.alert(entity.getData());
            } else if (entity.getEventType()==UserPresenter.By_GETSID_success){//获取sid 成功
                SIDBean data1 = (SIDBean) entity.getData();
                SPUtils.put(MyApplcation.ctx,null, SPContants.LOCK_SESSION,data1.getSid());
                SPUtils.put(MyApplcation.ctx,null,SPContants.ISLOCK,true);
                toRefreshData();
            }else if (entity.getEventType()==UserPresenter.By_GETSID_fail){
                ByAlert.alert(entity.getMsg());
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_icon:// 返回
                finish();
                break;
        }
    }


    private void toRefreshData() {
        sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
        isLock= (boolean) SPUtils.get(MyApplcation.ctx,null,SPContants.ISLOCK,false);

        if ("".equals(sid)){
            presenter.myKey(uid, "",isLock);
        }else {
            presenter.myKey(sid, "",isLock);
        }
    }
}
